package dbops

import (
	"edgex_back_management/model"
	"edgex_back_management/utils"
	"gopkg.in/mgo.v2/bson"
	"log"
)

func FindAllArticle(from, size int) ([]model.Article, error) {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("article")
	defer store.S.Close()

	articles := make([]model.Article, 16)
	err := c.Find(nil).Skip(from).Limit(size).Sort("-created").All(&articles)
	if err != nil {
		return nil, err
	}

	return articles, nil
}

func GetArticle(id string) (*model.Article, error) {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("article")
	defer store.S.Close()

	article := new(model.Article)
	// TODO: ID处理hex
	err := c.FindId(bson.ObjectIdHex(id)).One(&article)
	if err != nil {
		return nil, err
	}

	return article, nil
}

func PassArticle(id string) bool {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("article")
	defer store.S.Close()

	err := c.UpdateId(bson.ObjectIdHex(id), bson.M{"$set": bson.M{"approved": true, "modified": utils.NowInMilli()}})
	if err != nil {
		log.Printf("pass article error: %v", err)
		return false
	}

	return true
}

func RejectArticle(id string) bool {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("article")
	defer store.S.Close()

	err := c.UpdateId(bson.ObjectIdHex(id), bson.M{"$set": bson.M{"approved": false, "modified": utils.NowInMilli()}})
	if err != nil {
		log.Printf("pass article error: %v", err)
		return false
	}

	return true
}

func DeleteArticle(id string) bool {
	store := DS.DataStore()
	c := store.S.DB("edgex-club").C("article")
	defer store.S.Close()

	err := c.RemoveId(bson.ObjectIdHex(id))
	if err != nil {
		log.Printf("remove article: %s error: %v", id, err)
		return false
	}

	return true
}
